package com.ubox.mqtt_upush.utils;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class NetworkUtils {

	public static String getLocalv4IP() throws SocketException {
		Enumeration<NetworkInterface> interfs = NetworkInterface.getNetworkInterfaces();
		while (interfs.hasMoreElements()) {
			NetworkInterface interf = interfs.nextElement();
			Enumeration<InetAddress> addres = interf.getInetAddresses();
			while (addres.hasMoreElements()) {
				InetAddress in = addres.nextElement();
				if (in instanceof Inet4Address) {
					if (in.getHostAddress().startsWith("172.16") 
							|| in.getHostAddress().startsWith("192")) 
					{ return in.getHostAddress(); }
				}
				else if (in instanceof Inet6Address) {
				}
			}
		}

		return null;
	}

	public static void main(String[] args) throws SocketException {
		System.out.println("本地地址:" + getLocalv4IP());
	}

}
